package com.fintech.pangu.security.authentication.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 根据缓存请求中的参数做重定向的登录成功处理器
 *
 * @author Trust_FreeDom
 */
@Slf4j
public class RedirectBySavedRequestParameterAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    // 缓存请求中获取重定向URL的参数名
    private static final String SAVED_REQUEST_REDIRECT_PARAMETER_NAME = "redirect";

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication)
            throws ServletException, IOException {
        SavedRequest savedRequest = requestCache.getRequest(request, response);

        // 缓存请求为空，使用父类方法
        if (savedRequest == null) {
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        /**
         * 保持和SavedRequestAwareAuthenticationSuccessHandler相同逻辑
         * 如果isAlwaysUseDefaultTargetUrl==true 或 当前请求的targetUrlParameter有值，清楚请求缓存后，使用父类方法
         */
        String targetUrlParameter = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParameter != null && StringUtils.hasText(request
                .getParameter(targetUrlParameter)))) {
            requestCache.removeRequest(request, response);
            super.onAuthenticationSuccess(request, response, authentication);

            return;
        }

        clearAuthenticationAttributes(request);

        // 从缓存请求参数中获取重定向URL
        String targetUrl = getSavedRequestTargetUrl(savedRequest);
        logger.debug("Redirecting to DefaultSavedRequest Parameter Url: " + targetUrl);
        getRedirectStrategy().sendRedirect(request, response, targetUrl);
    }

    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }

    /**
     * 根据缓存请求参数获取重定向URL地址
     * @param savedRequest
     * @return
     */
    private String getSavedRequestTargetUrl(SavedRequest savedRequest) {
        String[] targetUrls = savedRequest.getParameterValues(SAVED_REQUEST_REDIRECT_PARAMETER_NAME);
        String targetUrl = "";
        if(targetUrls!=null && targetUrls.length>0){
            targetUrl = targetUrls[0];
        }
        return targetUrl;
    }

}
